package com.liuc.practice.ipersistent.config;

import com.liuc.practice.ipersistent.pojo.Configuration;
import com.liuc.practice.ipersistent.pojo.SqlMappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 该类用于解析传入的 InputStream 流
 * 并封装 Configuration 对象
 *
 * @Author Liu Chang
 * @Date 2020/12/13 6:58 上午
 */
public class ConfigurationBuilder {
    private Configuration configuration;

    public Configuration build(InputStream sqlMapConfigInputStream) throws DocumentException, PropertyVetoException {
        configuration = new Configuration();

        Document document = new SAXReader().read(sqlMapConfigInputStream);
        Element rootElement = document.getRootElement();

        List<Element> properties = rootElement.selectNodes("//property");
        DataSource dataSource = DataSourceBuilder.build(properties);
        configuration.setDataSource(dataSource);


        List<Element> mappers = rootElement.selectNodes("//mapper");
        Map<String, SqlMappedStatement> statementMap = SqlMappedStatementMapBuilder.build(mappers);
        configuration.setSqlMappedStatements(statementMap);
        return configuration;
    }
}
